<script lang="ts" setup>
import { useRouter } from "vue-router";
import { onMounted, ref } from "vue";
import { getMenusByModuleType, getMenusByModuleTypeAll } from "#/api/sys/menu";
import { ElMessage } from "element-plus";
import { useTabs } from "@vben/hooks";

// 声明全局变量类型
declare global {
  interface Window {
    globalVisible: boolean;
  }
}

const router = useRouter();
const isMobile = ref(false);
const hoverIndex = ref(0);
const clickIndex = ref(0);
const { closeTabsByGroup } = useTabs();

// 检测设备类型
const checkDeviceType = () => {
  isMobile.value = window.innerWidth <= 768;
};

// 获取菜单数据
const getMenus = async (moduleType: number) => {
  try {
    // 获取指定模块的菜单数据
    const { data } = await getMenusByModuleType({ moduleType });
    if (data && data.length > 0) {
      window.dispatchEvent(new Event("menusChange"));
      // 触发菜单更新事件
      window.dispatchEvent(new CustomEvent("menuUpdate", { detail: data }));
      return data;
    } else {
      ElMessage.error("没有权限访问，请联系管理员");
      return null;
    }
    // 获取全部菜单数据
    // const { data } = await getMenusByModuleTypeAll();
    // localStorage.setItem("menus", JSON.stringify(data));
    // 触发自定义事件通知菜单数据已更新
  } catch (error) {
    console.error("获取菜单数据失败:", error);
    ElMessage.error("获取菜单数据失败");
    return null;
  }
};

// 根据接口返回的菜单名称查找匹配的本地路由
const findMatchedRoute = async (menus: any[], moduleType: number): Promise<string | null> => {
  if (!menus || menus.length === 0) {
    return null;
  }

  // 动态导入对应的本地路由配置
  let localRoutes: any = null;
  
  try {
    if (moduleType === 1) {
      // 系统管理
      const sysModule = await import('#/router/routes/static/sys');
      localRoutes = sysModule.default;
    } else if (moduleType === 2) {
      // 任务管理
      const taskModule = await import('#/router/routes/static/taskmanagement');
      localRoutes = taskModule.default;
    } else if (moduleType === 3) {
      // 管控中心
      const dashboardModule = await import('#/router/routes/static/dashboard');
      localRoutes = dashboardModule.default;
    }

    if (!localRoutes || localRoutes.length === 0) {
      console.warn('未找到对应的本地路由配置');
      return null;
    }

    // console.log('========================================');
    // console.log('📋 接口返回的菜单:', JSON.stringify(menus, null, 2));

    // 递归查找匹配的路由（按接口顺序）
    const findRoute = (menuList: any[]): string | null => {
      for (const menu of menuList) {
        const menuName = menu.menuName || menu.name || menu.meta?.title;
        
        if (menuName) {
          // console.log(`✨ 正在匹配: "${menuName}"`);
          
          // 在本地路由中查找匹配
          const matchedPath = searchInRoutes(menuName, localRoutes[0]?.children || []);
          if (matchedPath) {
            // console.log(`✅ 找到匹配路由: "${menuName}" → ${matchedPath}`);
            // console.log('========================================\n');
            return matchedPath;
          }
        }
        
        // 递归查找子菜单
        if (menu.children && menu.children.length > 0) {
          const childPath = findRoute(menu.children);
          if (childPath) {
            return childPath;
          }
        }
      }
      return null;
    };

    // 在本地路由中搜索匹配的路径
    const searchInRoutes = (menuName: string, routes: any[]): string | null => {
      for (const route of routes) {
        // 递归查找子路由（深度优先）
        if (route.children && route.children.length > 0) {
          const childPath = searchInRoutes(menuName, route.children);
          if (childPath) {
            return childPath;
          }
        }
        
        // 匹配当前路由
        if (route.meta?.title === menuName && route.path && route.path !== '#') {
          if (route.component || !route.children || route.children.length === 0) {
            return route.path;
          }
        }
      }
      return null;
    };

    const result = findRoute(menus);
    if (!result) {
      console.warn('❌ 未找到任何匹配的路由');
      console.log('========================================\n');
    }
    return result;
  } catch (error) {
    console.error('加载本地路由配置失败:', error);
    return null;
  }
};

// 修改 tab 方法，根据接口返回的菜单跳转
const tab = async (fallbackPath, index: number) => {
  clickIndex.value = index;

  let moduleType = 1;
  let tabName = "sys";

  if (index === 1) {
    // 任务管理
    moduleType = 2;
    tabName = "task";
  } else if (index === 2) {
    // 系统管理
    moduleType = 1;
    tabName = "sys";
  }

  sessionStorage.setItem("tab", tabName);

  // 触发自定义事件通知 tabs 组件更新
  window.dispatchEvent(new Event('tabGroupChange'));

  // 清理不属于当前 tabGroup 的标签页
  await closeTabsByGroup(tabName);

  // 获取对应模块的菜单数据
  const menus = await getMenus(moduleType);

  // 只有在获取到菜单数据时才进行页面跳转
  if (menus && menus.length > 0) {
    const matchedPath = await findMatchedRoute(menus, moduleType);
    if (matchedPath) {
      navigateTo(matchedPath);
    } else {
      ElMessage.warning('未找到可访问的菜单');
    }
  }
};

// 修改 big 方法，添加权限检查
const big = async () => {
  clickIndex.value = 4;

  // 设置 tab group
  sessionStorage.setItem("tab", "big");
  // 触发自定义事件通知 tabs 组件更新
  window.dispatchEvent(new Event('tabGroupChange'));

  // 清理不属于当前 tabGroup 的标签页
  await closeTabsByGroup("big");

  // 获取管控中心菜单数据 (moduleType = 3)
  const menus = await getMenus(3);
  // 只有在获取到菜单数据时才进行页面跳转
  if (menus.length == 0) {
    ElMessage.error("没有权限访问，请联系管理员");
    return null;
  }
  let menu_url_list = [];
  menus.map((item, index) => {
    if (item.menuName == '态势大屏') {
      menu_url_list.push('/situationscreen')
    } else if (item.menuName == '飞行数据') {
      menu_url_list.push('/flightdata')
    } else if (item.menuName == '机场部署') {
      menu_url_list.push('/airportdeployment')
    } else if (item.menuName == '无人机监控') {
      menu_url_list.push('/dronemonitoring')
    }
  })
  // menus.map((item, index) => {
  //   if (item.menuName == '姿态大屏') {
  //     navigateTo("/situationscreen");
  //     return null;
  //   } else if (item.menuName == '飞行数据') {
  //     navigateTo("/flightdata");
  //     return null;
  //   } else if (item.menuName == '机场部署') {
  //     navigateTo("/airportdeployment");
  //     return null;
  //   } else if (item.menuName == '无人机监控') {
  //     navigateTo("/dronemonitoring");
  //     return null;
  //   }
  // })
  if (menu_url_list.length > 0) {
    if (menu_url_list.includes('/situationscreen')) {
      navigateTo("/situationscreen");
    } else if (menu_url_list.includes('/flightdata')) {
      navigateTo("/flightdata");
    } else if (menu_url_list.includes('/flightdata')) {
      navigateTo("/flightdata");
    } else if (menu_url_list.includes('/airportdeployment')) {
      navigateTo("/airportdeployment");
    } else if (menu_url_list.includes('/dronemonitoring')) {
      navigateTo("/dronemonitoring");
    }
  }
  // if (menus && menus.length > 0) {
  //   navigateTo("/situationscreen");
  //   navigateTo("/situationscreen");
  //   navigateTo("/situationscreen");
  //   navigateTo("/situationscreen");
  // }
};

// 处理路由跳转
const navigateTo = (path: string) => {
  // 使用 window 全局变量控制显示/隐藏
  // if (path === "/situationscreen") {
  //   // 管控中心显示横向菜单
  //   window.globalVisible = true;
  //   // 触发自定义事件通知其他组件
  //   window.dispatchEvent(
  //     new CustomEvent("globalVisibleChange", { detail: true })
  //   );
  // } else if (path === "/dashboard") {
  //   // 管控中心显示横向菜单
  //   window.globalVisible = true;
  //   // 触发自定义事件通知其他组件
  //   window.dispatchEvent(
  //     new CustomEvent("globalVisibleChange", { detail: true })
  //   );
  // } else {
  //   // 其他页面显示菜单
  //   window.globalVisible = true;
  //   // 触发自定义事件通知其他组件
  //   window.dispatchEvent(
  //     new CustomEvent("globalVisibleChange", { detail: true })
  //   );
  // }
  window.globalVisible = true;
  window.dispatchEvent(
    new CustomEvent("globalVisibleChange", { detail: true })
  );
  router.push(path);
};

// 响应式监听
onMounted(() => {
  checkDeviceType();
  window.addEventListener("resize", checkDeviceType);

  // 初始化全局变量
  window.globalVisible = true;
});
</script>

<template>
  <div class="page">
    <div class="title-container">
      <img src="/static/selectPage/selecctTitle.png" alt="选择页面标题" class="title" />
    </div>
    <div class="content">
      <div class="item" :class="{ clicked: clickIndex === 4 }" @click="big()" @mouseenter="hoverIndex = 1"
        @mouseleave="hoverIndex = 0">
        <img src="/static/selectPage/1.png" alt="管控中心" class="item-img" />
        <img src="/static/selectPage/title1.png" alt="" class="item-label" />
      </div>

      <div class="item purple" :class="{ clicked: clickIndex === 1 }" @click="tab('/routemanagement', 1)"
        @mouseenter="hoverIndex = 2" @mouseleave="hoverIndex = 0">
        <img src="/static/selectPage/2.png" alt="任务管理" class="item-img" />
        <img src="/static/selectPage/title2.png" alt="" class="item-label" />
      </div>

      <div class="item" :class="{ clicked: clickIndex === 2 }" @click="tab('/organizationalManagement', 2)"
        @mouseenter="hoverIndex = 3" @mouseleave="hoverIndex = 0">
        <img src="/static/selectPage/3.png" alt="系统管理" class="item-img" />
        <img src="/static/selectPage/title3.png" alt="" class="item-label" />
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
/* 移动端适配 */
@media (max-width: 768px) {
  .page {
    padding: 1rem;

    .title-container {
      margin-bottom: 1.5rem;
      animation: fadeInDown 0.8s ease-out;
    }

    .content {
      display: flex;
      flex-flow: column wrap;
      align-items: center;
      justify-content: space-around;

      .item {
        width: 80% !important;
        padding: 1.5rem;
        height: 300px !important;
        margin-bottom: 20px;
        position: relative;
        animation: fadeInUp 0.6s ease-out;

        .item-label {
          width: 70px !important;
          height: auto;
          position: absolute;
          bottom: 50px !important;
          left: 80px !important;
          animation: fadeIn 0.8s ease-out 0.3s both;
        }

        &.purple {
          width: 80%;
          position: relative !important;
          left: 0 !important;
          animation-delay: 0.2s;
        }

        .item-img {
          width: 100%;
          animation: fadeIn 0.8s ease-out;
        }
      }
    }
  }
}

.page {
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
  padding: 2rem;
  background: url("/static/selectPage/selectBg.png") center/cover no-repeat;
  background-size: cover;
  animation: fadeIn 0.8s ease-out;

  // 添加粒子动画效果
  &::before,
  &::after {
    content: "";
    position: absolute;
    width: 20px;
    height: 20px;
    border-radius: 50%;
    background: rgba(47, 105, 235, 0.1);
    animation: float 8s infinite ease-in-out;
  }

  &::before {
    top: 10%;
    left: 10%;
    animation-delay: 0s;
  }

  &::after {
    top: 80%;
    left: 90%;
    animation-delay: 2s;
  }

  // 添加点击动画效果
  &.clicked {
    animation: clickEffect 0.4s ease;
  }

  .title-container {
    margin-bottom: 5rem;
    text-align: center;
    animation: fadeInDown 1s ease-out;

    .title {
      max-width: 100%;
      height: auto;
      animation: pulse 2s infinite ease-in-out;
    }
  }

  .content {
    display: flex;
    align-items: center;
    justify-content: space-around;
    width: 100%;
    max-width: 1400px;
    position: relative;

    .item {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      width: 30%;
      height: 492px;
      text-align: center;
      cursor: pointer;
      background: url("/static/selectPage/bg.png") center/cover no-repeat;
      background-size: contain;
      border-radius: 12px;
      box-shadow: 0 4px 6px rgb(0 0 0 / 10%);
      transition: all 0.3s ease;
      position: relative;
      animation: fadeInUp 0.6s ease-out;

      // 为每个项目设置不同的动画延迟
      &:nth-child(1) {
        animation-delay: 0.1s;
      }

      &:nth-child(2) {
        animation-delay: 0.2s;
      }

      &:nth-child(3) {
        animation-delay: 0.3s;
      }

      &:hover {
        /* box-shadow: 0 10px 20px rgb(0 0 0 / 20%);*/
        transform: translateY(-5px);

        .item-img {
          transform: scale(1.05);
        }
      }

      &.purple {
        position: absolute;
        top: 0;
        left: 35%;
      }

      .item-img {
        max-width: 300px;
        height: auto;
        margin-bottom: 1.5rem;
        transition: transform 0.3s ease;
        animation: fadeIn 0.8s ease-out;
      }

      .item-label {
        width: 90px;
        height: auto;
        position: absolute;
        bottom: 120px;
        left: 110px;
        animation: bounceIn 0.8s ease-out 0.4s both;
      }
    }
  }
}

/* 动画关键帧 */
@keyframes fadeIn {
  from {
    opacity: 0;
  }

  to {
    opacity: 1;
  }
}

@keyframes fadeInDown {
  from {
    opacity: 0;
    transform: translateY(-30px);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(30px);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes bounceIn {

  0%,
  20%,
  40%,
  60%,
  80%,
  100% {
    transition-timing-function: cubic-bezier(0.215, 0.61, 0.355, 1);
  }

  0% {
    opacity: 0;
    transform: scale3d(0.3, 0.3, 0.3);
  }

  20% {
    transform: scale3d(1.1, 1.1, 1.1);
  }

  40% {
    transform: scale3d(0.9, 0.9, 0.9);
  }

  60% {
    opacity: 1;
    transform: scale3d(1.03, 1.03, 1.03);
  }

  80% {
    transform: scale3d(0.97, 0.97, 0.97);
  }

  100% {
    opacity: 1;
    transform: scale3d(1, 1, 1);
  }
}

@keyframes pulse {
  0% {
    transform: scale(1);
  }

  50% {
    transform: scale(1.02);
  }

  100% {
    transform: scale(1);
  }
}

@keyframes float {
  0% {
    transform: translateY(0) translateX(0);
  }

  25% {
    transform: translateY(-20px) translateX(10px);
  }

  50% {
    transform: translateY(0) translateX(20px);
  }

  75% {
    transform: translateY(20px) translateX(10px);
  }

  100% {
    transform: translateY(0) translateX(0);
  }
}

@keyframes clickEffect {
  0% {
    transform: scale(1);
  }

  50% {
    transform: scale(0.95);
  }

  100% {
    transform: scale(1);
  }
}
</style>